import os
import platform
import subprocess
import winreg  # Windows注册表操作
from dataclasses import dataclass


@dataclass
class BarTenderConfig:
    bin_path: str
    xml_path: str


class BarTenderHelper:
    def __init__(self, config: BarTenderConfig) -> None:
        self.config = config

    def is_windows(cls) -> bool:
        """检查当前系统是否为Windows"""
        return platform.system() == "Windows"

    def get_bartender_path(cls) -> str:
        """获取BarTender安装路径(仅Windows有效)，未找到返回空字符串"""
        if not cls.is_windows():
            return ""

        # 检查系统级和用户级注册表路径
        registry_paths = [
            (
                winreg.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
            ),
            (
                winreg.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
            ),
            (
                winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\CurrentVersion\Uninstall",
            ),
            (
                winreg.HKEY_CURRENT_USER,
                r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
            ),
        ]

        for root, path in registry_paths:
            try:
                with winreg.OpenKey(root, path) as key:
                    for i in range(0, winreg.QueryInfoKey(key)[0]):
                        subkey_name = winreg.EnumKey(key, i)
                        with winreg.OpenKey(key, subkey_name) as subkey:
                            try:
                                display_name = winreg.QueryValueEx(
                                    subkey, "DisplayName"
                                )[0]
                                if "BarTender" in display_name:
                                    install_location = winreg.QueryValueEx(
                                        subkey, "InstallLocation"
                                    )[0]
                                    return install_location
                            except WindowsError:
                                continue
            except WindowsError:
                continue

        return ""

    def run_xml(self, xml_path: str, param: dict = None):
        """运行BarTender XML文件"""
        if not self.is_windows():
            return False

        if not os.path.isfile(xml_path):
            return False

        if param is None:
            param = {}

        # 替换XML文件中的参数
        with open(xml_path, "r", encoding="utf-8") as file:
            xml_content = file.read()
            for key, value in param.items():
                xml_content = xml_content.replace("{{" + key + "}}", value)
        with open(
            r"1.xml",
            "w",
            encoding="utf-8",
        ) as file:
            file.write(xml_content)
        # 构建命令行参数

        cmd = [
            self.config.bin_path,  # 路径本身包含空格，subprocess会自动处理引号
            '/XMLScript="1.xml"',
        ]
        print(cmd)
        # 执行命令
        result = subprocess.run(
            cmd,
            shell=False,  # 对于包含空格的路径，shell=True更可靠
            capture_output=True,
            text=True,
        )
        print(result.stdout)
        print(result.stderr)

        return True


if __name__ == "__main__":
    config = BarTenderConfig(
        bin_path=r"C:/Program Files (x86)/Seagull/BarTender Suite/bartend.exe",
    )
    helper = BarTenderHelper(config)

    print(helper.get_bartender_path())
    print(helper.is_windows())
    helper.run_xml(
        r"C:\Users\Long\Documents\入学材料回执系统\project\bartender\print.xml",
        param={
            "name": "张三",
            "id": "20210101",
            "receipt": "回执",
        },
    )
